class Admin::CategoryGroupsController < Admin::AdminController
  filter_resource_access :additional_collection => {:restructure => :update}

  add_crumb("Správa skupin kategorií", :only => :index) {}
  add_crumb("Správa skupin kategorií", :admin_amount_types_path, :except => :index)
  add_crumb("Editace skupiny kategorií", :only => [:edit, :update]) {}
  add_crumb("Nová skupina kategorií", :only => [:new, :create]) {}

  def index
    @search = CategoryGroup.search(params[:search])
    @category_groups = @search.page(params[:page])
  end

  def create
    if @category_group.save
      redirect_to admin_category_groups_path, :notice => "Skupina kategorií byla úspěšně vytvořena. #{undo_link(@category_group)}"
    else
      render :action => :new
    end
  end

  def update
    if @category_group.update_attributes(params[:category_group])
      redirect_to edit_admin_category_group_path(@category_group), :notice => "Skupina kategorií byla úspěšně upravena. #{undo_link(@category_group)}"
    else
      render :action => :edit
    end
  end

  def destroy
    if @category_group.destroy
      flash[:notice] = "Skupina kategorií byla úspěšně smazána."
    else
      flash[:error] = "Skupinu kategorií se nepodařilo smazat."
    end

    redirect_to admin_category_groups_path
  end

  def restructure
    prev_id = params[:prev_id].to_i unless params[:prev_id].blank?
    next_id = params[:next_id].to_i unless params[:next_id].blank?
    node_id = params[:node_id].to_i unless params[:node_id].blank?
    parent_id = params[:parent_id].to_i unless params[:parent_id].blank?

    prev_id ||= 0
    next_id ||= 0
    node_id ||= 0
    parent_id ||= 0

    category = Category.find(node_id)

      if prev_id.zero? && next_id.zero?
        category.move_to_child_of parent_id
      elsif !prev_id.zero?
        category.move_to_right_of prev_id
      elsif !next_id.zero?
        category.move_to_left_of next_id
      end

      category.make_permalink
      category.save

    render :nothing => true
  end
end
